import pymysql


# 创建数据库工具类
class DBUtil:
    # 创建连接
    @classmethod
    def myconn_func(cls):
        myconn = pymysql.connect(host='211.103.136.244',
                                 port=7061,
                                 user='student',
                                 password='iHRM_student_2022',
                                 database='ihrm',
                                 charset='utf8')
        return myconn

    @classmethod
    # 创建数据库查询方法
    def select_sql(cls, sql):
        myconn = None
        mycur = None
        data = None
        try:
            # 创建连接
            myconn = DBUtil.myconn_func()
            # myconn = pymysql.connect(host='211.103.136.244',
            #                          port=7061,
            #                          user='student',
            #                          password='iHRM_student_2022',
            #                          database='test_db',
            #                          charset='utf8')
            # 获取游标
            mycur = myconn.cursor()
            # 用游标实例 执行 sql语句
            mycur.execute(sql)
            # 获取结果集内的数据
            data = mycur.fetchone()
        except Exception as result:
            print('代码出错:', result)
        finally:
            # 关闭游标
            mycur.close()
            # 关闭连接
            myconn.close()
            return data

    @classmethod
    # 封装
    def diu_sql(cls, sql):
        myconn = None
        mycur = None
        try:
            # 创建连接
            myconn = DBUtil.myconn_func()
            # myconn = pymysql.connect(host='211.103.136.244',
            #                          port=7061,
            #                          user='student',
            #                          password='iHRM_student_2022',
            #                          database='test_db',
            #                          charset='utf8')
            # 获取游标
            mycur = myconn.cursor()
            # 用游标实例 执行 sql语句
            mycur.execute(sql)
            # 获取事务提交
            myconn.commit()
        except Exception as result:
            print('代码出错:', result)
            myconn.rollback()
        finally:
            # 关闭游标
            mycur.close()
            # 关闭连接
            myconn.close()
